package chu.dejian.ui.fragmet;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.TextView;

import chu.dejian.alarm.Alarm;
import chu.dejian.alarm.Alarms;

import com.sam.blemodule.R;
import chu.dejian.dialogOrMenu.AlarmRepeatDialog;
import com.sam.ui.base.fragment.BaseFragment;
import com.sam.utils.L;
import com.sam.utils.T;
import com.sam.widget.switcher.SwitchButton;
import com.sam.widget.headerBar.BaseHeaderView;
import com.sam.widget.headerBar.LeftImgTitleRightImgBar;
import com.sam.widget.time_picker.TimePicker;

public class MeasureAlarmSetFragment extends BaseFragment {
	private static MeasureAlarmSetFragment instance;
	public synchronized static MeasureAlarmSetFragment getInstance(){
		if(instance == null){
			instance = new MeasureAlarmSetFragment();
		}
		return instance;
	}

	private LeftImgTitleRightImgBar header;
	private TimePicker timePicker;
	private View setRepeatLayout,setRingtoneLayout,setEnableLayout, deleteAlarmBtn;
	private SwitchButton enableClockSwitcher;
	private TextView repeatValueStrTV,ringtoneTV;
	private int mId = -1;
	Alarm alarm;
	private AlarmRepeatDialog alarmRepeatDialog;
	private Uri ringtoneUrl;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_measure_alarm_set);
	}

	@Override
	public void findView() {
		header = (LeftImgTitleRightImgBar) findViewById(R.id.header);
		timePicker = (TimePicker) findViewById(R.id.time_picker);
		setRepeatLayout = findViewById(R.id.set_repate_layout);
		setRingtoneLayout = findViewById(R.id.set_ringtone_layout);
		setEnableLayout = findViewById(R.id.set_enable_layout);
		deleteAlarmBtn = findViewById(R.id.delete_alarm_btn);
		enableClockSwitcher = (SwitchButton) findViewById(R.id.clock_enable_switcher);
		repeatValueStrTV = (TextView) findViewById(R.id.repeat_value_str);
		ringtoneTV = (TextView) findViewById(R.id.clock_ringtone_name);
	}

	@Override
	public void initView() {
		alarmRepeatDialog = new AlarmRepeatDialog(getActivity());
		header.setOnHeaderClickListener(onHeaderClickListener);
		setRepeatLayout.setOnClickListener(onClickListener);
		setRingtoneLayout.setOnClickListener(onClickListener);
		setEnableLayout.setOnClickListener(onClickListener);
		deleteAlarmBtn.setOnClickListener(onClickListener);
		enableClockSwitcher.setOnCheckChangeListener(onCheckChangeListener);
		alarmRepeatDialog.setOnDismissListener(onDismissListener);
	}

	private DialogInterface.OnDismissListener onDismissListener = new DialogInterface.OnDismissListener() {
		@Override
		public void onDismiss(DialogInterface dialog) {
			alarm.daysOfWeek = alarmRepeatDialog.getDaysOfWeek();
			repeatValueStrTV.setText(alarmRepeatDialog.getDaysOfWeek().toString(getActivity(),true));
		}
	};

	@Override
	public void onResume() {
		super.onResume();
		Bundle bundle = getArgumentBundle();
		if(bundle == null || bundle.getInt(Alarms.ALARM_ID, -1) == -1) { //添加闹钟
			mId = -1;
			deleteAlarmBtn.setVisibility(View.GONE);
			alarm = new Alarm();
			return;
		}
		mId = bundle.getInt(Alarms.ALARM_ID, -1);
		alarm = Alarms.getAlarm(getActivity().getContentResolver(), mId);
		if (alarm != null) {
			restoreAlarmDataToUI(alarm);
			deleteAlarmBtn.setVisibility(View.VISIBLE);
		} else deleteAlarmBtn.setVisibility(View.GONE);
	}

	private void restoreAlarmDataToUI(Alarm alarm){
		timePicker.setTime(alarm.hour, alarm.minutes);
		repeatValueStrTV.setText(alarm.daysOfWeek.toString(getActivity(),true));
		if(alarm.ringtoneUrl != null && !alarm.ringtoneUrl.equals(Settings.System.DEFAULT_ALARM_ALERT_URI))
			ringtoneTV.setText(RingtoneManager.getRingtone(getActivity(),alarm.ringtoneUrl).getTitle(getActivity()));
		enableClockSwitcher.setChecked(alarm.enabled);
	}

	private BaseHeaderView.OnHeaderClickListener onHeaderClickListener = new BaseHeaderView.OnHeaderClickListener() {
		@Override
		public void onHeaderLeftClicked() {
			backToPreviewFragment();
		}

		@Override
		public void onHeaderRightClicked() {
			saveAlarm();
			backToPreviewFragment();
		}
	};

	private View.OnClickListener onClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			int i = v.getId();
			if (i == R.id.set_repate_layout) {
				if (alarm != null) alarmRepeatDialog.setRepeatDaysValue(alarm.daysOfWeek);
				if (!alarmRepeatDialog.isShowing()) alarmRepeatDialog.show();

			} else if (i == R.id.set_ringtone_layout) {
				startPickRingtone();

			} else if (i == R.id.set_enable_layout) {
				enableClockSwitcher.setChecked(!enableClockSwitcher.isChecked());

			} else if (i == R.id.delete_alarm_btn) {
				deleteAlarm();

			}
		}
	};

	private SwitchButton.OnCheckChangeListener onCheckChangeListener = new SwitchButton.OnCheckChangeListener() {
		@Override
		public void OnCheck(SwitchButton switchButton, boolean isChecked) {
//			if(isChecked) popAlarmSetToast(SetAlarm.this, mHour, mMinutes, mRepeatPref.getDaysOfWeek());
		}
	};

	private long saveAlarm() {
		Alarm a = new Alarm();
		a.id = mId;
		a.enabled = enableClockSwitcher.isChecked();
		a.hour = timePicker.getCurrentHour();
		a.minutes = timePicker.getCurrentMinute();
		a.daysOfWeek = alarm.daysOfWeek;
//		alarm.vibrate = mVibratePref.isChecked();
//		alarm.label = mLabel.getText();
		a.ringtoneUrl = ringtoneUrl;

		long time;
		if (a.id == -1) {
			time = Alarms.addAlarm(getActivity(), a);
			// addAlarm populates the alarm with the new id. Update mId so that
			// changes to other preferences update the new alarm.
			mId = a.id;
		} else {
			time = Alarms.setAlarm(getActivity(), a);
		}
		return time;
	}

	private void deleteAlarm() {
		new AlertDialog.Builder(getActivity())
				.setTitle(getString(R.string.delete_alarm))
				.setMessage(getString(R.string.delete_alarm_confirm))
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface d, int w) {
								Alarms.deleteAlarm(getActivity(), mId);
								backToPreviewFragment();
							}
						})
				.setNegativeButton(android.R.string.cancel, null)
				.show();
	}

	/**
	 * Display a toast that tells the user how long until the alarm
	 * goes off.  This helps prevent "am/pm" mistakes.
	 */
	static void popAlarmSetToast(Context context, int hour, int minute, Alarm.DaysOfWeek daysOfWeek) {
		popAlarmSetToast(context, Alarms.calculateAlarm(hour, minute, daysOfWeek).getTimeInMillis());
	}

	static void popAlarmSetToast(Context context, long timeInMillis) {
		String toastText = formatToast(context, timeInMillis);
		T.showLong(context,toastText);
	}

	/**
	 * format "Alarm set for 2 days 7 hours and 53 minutes from
	 * now"
	 */
	static String formatToast(Context context, long timeInMillis) {
		long delta = timeInMillis - System.currentTimeMillis();
		long hours = delta / (1000 * 60 * 60);
		long minutes = delta / (1000 * 60) % 60;
		long days = hours / 24;
		hours = hours % 24;

		String daySeq = (days == 0) ? "" : (days == 1) ? context.getString(R.string.day) : context.getString(R.string.days, Long.toString(days));
		String minSeq = (minutes == 0) ? "" : (minutes == 1) ? context.getString(R.string.minute) : context.getString(R.string.minutes, Long.toString(minutes));
		String hourSeq = (hours == 0) ? "" : (hours == 1) ? context.getString(R.string.hour) : context.getString(R.string.hours, Long.toString(hours));

		boolean dispDays = days > 0;
		boolean dispHour = hours > 0;
		boolean dispMinute = minutes > 0;

		int index = (dispDays ? 1 : 0) | (dispHour ? 2 : 0) | (dispMinute ? 4 : 0);

		String[] formats = context.getResources().getStringArray(R.array.alarm_set);
		return String.format(formats[index], daySeq, hourSeq, minSeq);
	}


	private void startPickRingtone(){
		Intent intent = new Intent();
		intent.setAction(RingtoneManager.ACTION_RINGTONE_PICKER);
		// Allow user to pick 'Default'
		//intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
		intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE,getResources().getString(R.string.set_alarm_ringtone));
		// Show only ringtones
		intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM);
		// Don't show 'Silent'
		intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);

		//Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
		// Put checkmark next to the current ringtone for this contact
		if(ringtoneUrl != null)
		{
			intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, ringtoneUrl);
			//intent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, ringtoneUrl);
		}
		// Launch!
		startActivityForResult(intent, Activity.RESULT_FIRST_USER);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(resultCode != Activity.RESULT_OK) return;
		try
		{
			ringtoneUrl = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
			if (ringtoneUrl != null) RingtoneManager.setActualDefaultRingtoneUri(getActivity(), RingtoneManager.TYPE_ALARM, ringtoneUrl);
			ringtoneTV.setText(ringtoneUrl.getLastPathSegment());
		} catch (Exception e)
		{
			L.e("选择铃声返回结果解析错误");
			e.printStackTrace();
		}
	}

}
